package com.example.eda.controller;


import com.example.eda.config.RabbitMQConfig;
import com.example.eda.event.LoginEvent;
import com.example.eda.model.User;
import com.example.eda.service.UserService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;


@RestController
@RequestMapping("/users")
public class UserController {
    private final UserService userService;
    private final RabbitTemplate rabbitTemplate;

    @Autowired
    public UserController(UserService userService, RabbitTemplate rabbitTemplate) {
        this.userService = userService;
        this.rabbitTemplate = rabbitTemplate;
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody User user) {
        User loggedInUser = userService.login(user.getUsername(), user.getPassword());
        if (loggedInUser != null) {
            // 发布登录事件
            LoginEvent event = new LoginEvent(
                    loggedInUser.getUsername(),
                    loggedInUser.getId(),
                    LocalDateTime.now()
            );
            rabbitTemplate.convertAndSend(
                    "login_exchange",  // 交换机名称
                    "login.routing.key", // 路由键
                    event
            );

            return ResponseEntity.ok(loggedInUser);
        } else {
            return ResponseEntity.status(401).body("Invalid credentials");
        }
    }

    @PostMapping
    public ResponseEntity<User> register(@RequestBody User user) {
        userService.register(user);
        return ResponseEntity.ok(user);
    }

    @PutMapping("/{id}")
    public ResponseEntity<User> update(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        userService.updateUser(user);
        return ResponseEntity.ok(user);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> delete(@PathVariable Long id) {
        userService.deleteUser(id);
        return ResponseEntity.ok("User deleted");
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getUser(@PathVariable Long id) {
        return ResponseEntity.ok(userService.getUserById(id));
    }

    @GetMapping("/test-mq")
    public String testMQ() {
        try {
            rabbitTemplate.convertAndSend("test_exchange", "test", "ping");
            return "MQ连接成功";
        } catch (Exception e) {
            return "MQ连接失败: " + e.getMessage();
        }
    }

}
